//
//  SEGSignActivityDetailViewModel.m
//  Commom
//
//  Created by Clavis on 2020/6/18.
//

#import "SEGSignActivityDetailViewModel.h"
#import <SEGModel/SEGActivityManager.h>

@interface SEGSignActivityDetailViewModel ()

/** 网络请求管理对象 */
@property (nonatomic, strong) SEGActivityManager *activityManager;

@end

@implementation SEGSignActivityDetailViewModel

/// 活动详情信号量
- (RACSignal *)activityDetailSignal {
    if (!_activityDetailSignal) {
        @weakify(self);
        _activityDetailSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.activityManager requestQueryActivityWithActId:self.actId finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                    
                    //活动详情请求成功，统计浏览次数（第一次加载的时候才统计浏览）
                    [self.activityManager requestBrowseSharePraiseWithActId:self.actId actionType:@"1" finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    }];
                }
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }
    return _activityDetailSignal;
}

/// 签到详情信号量
- (RACSignal *)signDetailSignal {
    if (!_signDetailSignal) {
        @weakify(self);
        _signDetailSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.activityManager requestQuerySignBySignId:self.activityManager.detailModel.actObj finished:^(BOOL isSuccessed,id result, NSString* codeType, NSString* errorMessage) {
                if (isSuccessed) {
                    BOOL isNeedSign = NO;
                    if (![self.activityManager.signModel.hadSign isEqualToString:@"1"]) { // 未签到
                        // 去签到
                        //[weakSelf req_sign];
                        isNeedSign = YES;
                    }
                    [subscriber sendNext:@(isNeedSign)];
                    [subscriber sendCompleted];
                }
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }
    return _signDetailSignal;
}

/// 签到信号量
- (RACSignal *)submitSignSignal {
    if (!_submitSignSignal) {
        @weakify(self);
        _submitSignSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            // 活动是否在进行中
            if ([self.activityManager.detailModel.actStatus integerValue] == SEGActivityStatus_NotBegin) {
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:@"亲！活动还未开始，请稍后再试哦！"}];
                [subscriber sendError:error];
                return nil;
            }
            
            // 活动是否已结束
            if ([self.activityManager.detailModel.actStatus integerValue] == SEGActivityStatus_Over) {
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:@"亲！活动已经结束了，下次早点来吧！"}];
                [subscriber sendError:error];
                return nil;
            }
            
            // 活动参与对象不包含未认证用户
            if (![self.activityManager.detailModel.joinObj containsObject:@"0"]) {
                SEGQueryauthinfoDataModel *data = [SEGQueryauthinfoManager sharedManager].QueryAuthInfo.data;
                SEGProfileModel *model = [SEGProfileManager sharedManager].profile;
                if ([model.type intValue] == kUserTypeZiLBuQ) {//未认证用户
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{SEGActicityErrorNoAuthTitleKey:SEGBasicBussinessStringDefine.promptUserAuthentication}];
                    [subscriber sendError:error];
                    return nil;
                }
            }
            
            [self.activityManager requestSignByActId:self.actId finished:^(BOOL isSuccessed,id result, NSString* codeType, NSString* errorMessage) {
                if (isSuccessed) {
                    // 签到成功弹窗
                    NSInteger value = [self.activityManager.userSignModel.awardValue integerValue];
                    NSInteger type = 1; // 默认为成长值
                    if ([self.activityManager.userSignModel.awardType integerValue] == 1) { // 积分
                        type = 0;
                    }
                    [subscriber sendNext:RACTuplePack(errorMessage, @(value), @(type))];
                    [subscriber sendCompleted];
                    
                    // 签到成功 触发签到行为积分
                    [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.participateActivity module:SEGIntegralModule.activityDetail businessID:self.actId finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    }];
                }
            
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }
    return _submitSignSignal;
}

/// 获取任务列表信号量
- (RACSignal *)fetchTaskListSignal {
    if (!_fetchTaskListSignal) {
        _fetchTaskListSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL, @"/cms-api/task/queryTaskList", nil];
            [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    if ([result isKindOfClass:[NSDictionary class]] && [result[@"data"] isKindOfClass:[NSDictionary class]] && [result[@"data"][@"mainTaskList"] isKindOfClass:[NSArray class]]) {
                        NSArray *taskDateArray = result[@"data"][@"mainTaskList"];
                        NSArray<SEGActivityTaskModel *> *taskArray = [taskDateArray.rac_sequence map:^id _Nullable(id  _Nullable value) {
                            SEGActivityTaskModel *taskModel = [SEGActivityTaskModel yy_modelWithDictionary:value];
                            NSMutableArray<SEGActivityChildTaskModel *> *completedTaskList = [NSMutableArray array];
                            NSMutableArray<SEGActivityChildTaskModel *> *incompletTaskList = [NSMutableArray array];
                            // 对子任务进行排序，未完成的任务放在前面
                            [taskModel.childTaskList enumerateObjectsUsingBlock:^(SEGActivityChildTaskModel * _Nonnull childTaskModel, NSUInteger idx, BOOL * _Nonnull stop) {
                                if (childTaskModel.whetherComplete == 1) {
                                    [completedTaskList addObject:childTaskModel];
                                } else {
                                    [incompletTaskList addObject:childTaskModel];
                                }
                            }];
                            [incompletTaskList addObjectsFromArray:completedTaskList];
                            taskModel.childTaskList = [incompletTaskList copy];
                            return taskModel;
                        }].array;
                        [subscriber sendNext:taskArray];
                        [subscriber sendCompleted];
                    } else {
                        isSuccessed = NO;
                        errorMessage = kNetworkErrorMessage;
                    }
                }
                if (!isSuccessed) {
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            return nil;
        }];
    }
    return _fetchTaskListSignal;
}

/// 领取任务信号量
- (RACCommand *)receiveTaskCommand {
    if (!_receiveTaskCommand) {
        _receiveTaskCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            NSString *exampleId = ValueToString(input);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL, @"/cms-api/task/receiveTask", nil];
                [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:@{@"exampleId":exampleId} finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (!isSuccessed) {
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                    }
                    [subscriber sendNext:errorMessage];
                    [subscriber sendCompleted];
                }];
                return nil;
            }];
        }];
    }
    return _receiveTaskCommand;
}

/// 积分抢兑信号量
- (RACSignal *)integralEexchangeSignal {
    if (!_integralEexchangeSignal) {
        _integralEexchangeSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [[SEGAnalyseBehaviorManager sharedManager] requestIntegralEexchangeDataWithFinish:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed && [result isKindOfClass:[NSArray class]]) {
                    [subscriber sendNext:[result copy]];
                    [subscriber sendCompleted];
                }
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }
    return _integralEexchangeSignal;
}

/// 总积分信号量
- (RACSignal *)totalIntegralSignal {
    if (!_totalIntegralSignal) {
        @weakify(self);
        _totalIntegralSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.activityManager requestMyCardV2WithDict:nil Finished:^(BOOL isSuccessed,id result, NSString* codeType, NSString* errorMessage) {
                if (isSuccessed) {
                    __block NSInteger value = 0;
                    [self.activityManager.seg_segbanalcesmodel enumerateObjectsUsingBlock:^(SEGBanalcesModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([obj.balancetype integerValue] == 5) { // 积分
                            value += [obj.balance integerValue];
                        }
                    }];
                    [subscriber sendNext:[NSString stringWithFormat:@"%ld",(long)value]];
                    [subscriber sendCompleted];
                }
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }
    return _totalIntegralSignal;
}

/// 广告数据信号量
- (RACSignal *)adListSignal {
    if (!_adListSignal) {
        _adListSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [[SEGAdvlistManager sharedManager] segRequestAdvlistWithPositionType:SEGAdvlistType_Sign completed:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull codeType, NSString * _Nonnull errorMessage) {
                if (isSuccessed) {
                    [subscriber sendNext:result];
                    [subscriber sendCompleted];
                }
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }
    return _adListSignal;
}

/// 查询任务详情
- (RACCommand *)taskDetailCommand {
    if (!_taskDetailCommand) {
        _taskDetailCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            NSString *exampleId = ValueToString(input);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL, @"/cms-api/task/queryTaskDetail", nil];
                [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:@{@"exampleId":exampleId} finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        if ([result isKindOfClass:[NSDictionary class]] && [result[@"data"] isKindOfClass:[NSDictionary class]]) {
                            SEGActivityTaskModel *model = [SEGActivityTaskModel yy_modelWithJSON:result[@"data"]];
                            NSMutableArray<SEGActivityChildTaskModel *> *completedTaskList = [NSMutableArray array];
                            NSMutableArray<SEGActivityChildTaskModel *> *incompletTaskList = [NSMutableArray array];
                            // 对子任务进行排序，未完成的任务放在前面
                            [model.childTaskList enumerateObjectsUsingBlock:^(SEGActivityChildTaskModel * _Nonnull childTaskModel, NSUInteger idx, BOOL * _Nonnull stop) {
                                if (childTaskModel.whetherComplete == 1) {
                                    [completedTaskList addObject:childTaskModel];
                                } else {
                                    [incompletTaskList addObject:childTaskModel];
                                }
                            }];
                            [incompletTaskList addObjectsFromArray:completedTaskList];
                            model.childTaskList = [incompletTaskList copy];
                            
                            [subscriber sendNext:model];
                            [subscriber sendCompleted];
                        } else {
                            isSuccessed = NO;
                            errorMessage = kNetworkErrorMessage;
                        }
                    }
                    if (!isSuccessed) {
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                    }
                }];
                return nil;
            }];
        }];
    }
    return _taskDetailCommand;
}

/// 获取签到Id
- (RACSignal *)signIdSignal {
    if (!_signIdSignal) {
        @weakify(self);
        _signIdSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.activityManager requestIsSignShow:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    self.signId = ValueToString(result[@"data"][@"actId"]);
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }
            }];
            return nil;
        }];
    }
    return _signIdSignal;
}

#pragma mark - Getter
- (SEGActivityManager *)activityManager {
    if (!_activityManager) {
        _activityManager = [[SEGActivityManager alloc] init];
    }
    return _activityManager;
}

- (void)setActId:(NSString *)actId {
    _actId = ValueToString(actId);
}

- (SEGActivityDetailModel *)detailModel {
    return _activityManager.detailModel;
}

- (SEGActivitySignModel *)signModel {
    return _activityManager.signModel;
}

@end
